#!/usr/bin/env node

import inquirer from 'inquirer';
import chalk from 'chalk';
import { AutomationEngine } from './modules/automation-engine';
import { config } from './config';
import { logger } from './utils/logger';
import { SSHConfig } from './types';
import { ServerConfigManager, ServerProfile } from './utils/server-config';
import { AITodoManager } from './utils/ai-todo-manager';
import { DeepSeekClient } from './modules/deepseek-client';

class SimpleCLI {
  private engine: AutomationEngine | null = null;
  private serverManager: ServerConfigManager;
  private todoManager: AITodoManager | null = null;
  private deepseekClient: DeepSeekClient;

  constructor() {
    this.serverManager = new ServerConfigManager();
    this.deepseekClient = new DeepSeekClient(config.deepseek);
  }

  async start(): Promise<void> {
    console.log(chalk.cyan('🚀 SSH-DeepSeek 自动化运维系统'));
    console.log(chalk.gray('版本: 1.0.0 | 智能运维助手\n'));

    try {
      // 选择或配置服务器
      const sshConfig = await this.selectServer();

      // 连接到服务器
      await this.connectToServer(sshConfig);

      // 开始交互循环
      await this.startMainLoop();

    } catch (error) {
      console.log(chalk.red(`❌ 启动失败: ${error}`));
      process.exit(1);
    }
  }

  private async selectServer(): Promise<SSHConfig> {
    const profiles = this.serverManager.getFormattedList();

    if (profiles.length === 1) {
      // 只有"添加新服务器"选项
      return await this.getNewSSHConfig();
    }

    const { selectedServer } = await inquirer.prompt([{
      type: 'list',
      name: 'selectedServer',
      message: '选择服务器:',
      choices: profiles,
      pageSize: 10
    }]);

    if (selectedServer === 'new') {
      return await this.getNewSSHConfig();
    }

    const profile = this.serverManager.getProfile(selectedServer);
    if (!profile) {
      throw new Error('服务器配置不存在');
    }

    // 更新最后使用时间
    this.serverManager.updateLastUsed(selectedServer);

    console.log(chalk.green(`📡 已选择服务器: ${profile.name} (${profile.config.host}:${profile.config.port})`));
    return profile.config;
  }

  private async getNewSSHConfig(): Promise<SSHConfig> {
    console.log(chalk.yellow('📝 请输入SSH服务器连接信息:'));

    const answers = await inquirer.prompt([
      {
        type: 'input',
        name: 'name',
        message: '服务器名称 (用于保存配置):',
        validate: (input: string) => {
          if (!input.trim()) return '请输入服务器名称';
          return true;
        }
      },
      {
        type: 'input',
        name: 'host',
        message: '服务器IP地址或域名:',
        validate: (input: string) => {
          if (!input.trim()) return '请输入服务器地址';
          return true;
        }
      },
      {
        type: 'input',
        name: 'username',
        message: 'SSH用户名:',
        default: 'root',
        validate: (input: string) => {
          if (!input.trim()) return '请输入用户名';
          return true;
        }
      },
      {
        type: 'password',
        name: 'password',
        message: 'SSH密码:',
        mask: '*',
        validate: (input: string) => {
          if (!input) return '请输入密码';
          return true;
        }
      },
      {
        type: 'number',
        name: 'port',
        message: 'SSH端口:',
        default: 22
      },
      {
        type: 'input',
        name: 'description',
        message: '描述 (可选):'
      },
      {
        type: 'confirm',
        name: 'save',
        message: '是否保存此服务器配置?',
        default: true
      }
    ]);

    const sshConfig: SSHConfig = {
      host: answers.host.trim(),
      username: answers.username.trim(),
      password: answers.password,
      port: answers.port || 22,
      timeout: 30000
    };

    if (answers.save) {
      const profileId = this.serverManager.addProfile(
        answers.name.trim(),
        sshConfig,
        answers.description?.trim()
      );
      console.log(chalk.green(`💾 服务器配置已保存，ID: ${profileId}`));
    }

    return sshConfig;
  }

  private async connectToServer(sshConfig: SSHConfig): Promise<void> {
    console.log(chalk.yellow('\n🔌 正在连接SSH服务器...'));
    console.log(chalk.gray(`连接到: ${sshConfig.username}@${sshConfig.host}:${sshConfig.port}`));

    try {
      this.engine = new AutomationEngine(sshConfig, config.deepseek);
      await this.engine.initializeSSHConnection(sshConfig);

      console.log(chalk.green('✅ SSH连接成功！'));

      // 获取系统信息
      console.log(chalk.yellow('📊 获取系统信息...'));
      const systemInfo = await this.getSystemInfo();
      console.log(chalk.gray(systemInfo));

    } catch (error) {
      throw new Error(`SSH连接失败: ${error}`);
    }
  }

  private async getSystemInfo(): Promise<string> {
    if (!this.engine) return '';

    try {
      const result = await this.engine.executeCustomCommand('uname -a && whoami && pwd');
      return result.success ? result.stdout : '获取系统信息失败';
    } catch {
      return '获取系统信息失败';
    }
  }

  private async startMainLoop(): Promise<void> {
    console.log(chalk.cyan('\n🤖 智能运维助手已就绪！'));
    console.log(chalk.gray('您可以用自然语言描述需要执行的运维任务，我会自动执行并提供反馈。'));
    console.log(chalk.gray('输入 "exit" 或 "quit" 退出程序\n'));

    while (true) {
      try {
        const { task } = await inquirer.prompt([{
          type: 'input',
          name: 'task',
          message: '💬 请描述您需要执行的运维任务:',
          validate: (input: string) => {
            if (!input.trim()) return '请输入任务描述';
            if (input.trim().toLowerCase() === 'exit' || input.trim().toLowerCase() === 'quit') return true;
            if (input.trim().length < 3) return '任务描述太短，请详细描述';
            return true;
          }
        }]);

        const taskInput = task.trim();

        if (taskInput.toLowerCase() === 'exit' || taskInput.toLowerCase() === 'quit') {
          await this.cleanup();
          console.log(chalk.green('👋 再见！'));
          process.exit(0);
        }

        await this.executeTask(taskInput);

      } catch (error) {
        console.log(chalk.red(`❌ 发生错误: ${error}`));
        console.log(chalk.yellow('🔄 请重新输入任务或输入 "exit" 退出\n'));
      }
    }
  }

  private async executeTask(taskDescription: string): Promise<void> {
    if (!this.engine) {
      console.log(chalk.red('❌ SSH连接已断开'));
      return;
    }

    console.log(chalk.yellow(`\n🎯 任务: ${taskDescription}`));

    try {
      // 初始化AI Todo管理器并生成执行计划
      this.todoManager = new AITodoManager(this.deepseekClient);
      await this.todoManager.generateTodoList(taskDescription);

      // 开始执行任务
      console.log(chalk.yellow('\n🤖 开始执行任务...'));

      // 显示当前状态
      this.todoManager.displayCurrentStatus();

      // 自动执行任务（无需用户确认）
      const task = await this.engine.executeAutomatedTask(taskDescription);

      // 更新Todo状态
      if (this.todoManager) {
        if (task.status === 'completed') {
          // 标记所有步骤为完成
          const todos = this.todoManager.getTodos();
          todos.forEach((_, index) => {
            this.todoManager!.completeStep(index, true);
          });
        } else if (task.status === 'failed') {
          // 根据结果标记相应步骤
          const nextStep = this.todoManager.getNextStepIndex();
          if (nextStep >= 0) {
            this.todoManager.completeStep(nextStep, false);
          }
        }

        // 显示最终结果
        console.log(chalk.cyan('\n📋 执行总结:'));
        const summary = this.todoManager.getCompletionSummary();
        console.log(chalk.green(`✅ 完成: ${summary.completed}/${summary.total}`));
        if (summary.failed > 0) {
          console.log(chalk.red(`❌ 失败: ${summary.failed}`));
        }
        if (summary.duration) {
          console.log(chalk.gray(`⏱️  用时: ${summary.duration}`));
        }
      }

      // 显示执行结果
      this.displayTaskResult(task);

    } catch (error) {
      console.log(chalk.red(`❌ 任务执行失败: ${error}`));

      // 更新Todo状态
      if (this.todoManager) {
        const nextStep = this.todoManager.getNextStepIndex();
        if (nextStep >= 0) {
          this.todoManager.completeStep(nextStep, false);
        }
      }

      // 尝试获取错误的详细信息
      if (error instanceof Error && error.message.includes('命令执行')) {
        console.log(chalk.yellow('🔧 尝试分析错误并提供解决方案...'));
        await this.handleTaskError(taskDescription, error);
      }
    }

    console.log(chalk.gray('\n' + '─'.repeat(60) + '\n'));
  }

  private displayTaskResult(task: any): void {
    const statusIcon = task.status === 'completed' ? '✅' : '❌';
    console.log(chalk.cyan(`\n${statusIcon} 任务${task.status === 'completed' ? '完成' : '失败'}`));

    if (task.commands && task.commands.length > 0) {
      console.log(chalk.cyan('📝 执行的命令:'));
      task.commands.forEach((cmd: string, index: number) => {
        console.log(chalk.white(`  ${index + 1}. ${cmd}`));
      });
    }

    if (task.results && task.results.length > 0) {
      console.log(chalk.cyan('\n📊 执行结果:'));
      task.results.forEach((result: any, index: number) => {
        const icon = result.success ? '✅' : '❌';
        console.log(chalk.white(`\n${icon} 命令 ${index + 1}: ${result.command}`));

        if (result.stdout && result.stdout.trim()) {
          console.log(chalk.green('📤 输出:'));
          console.log(chalk.gray(this.formatOutput(result.stdout)));
        }

        if (result.stderr && result.stderr.trim()) {
          console.log(chalk.red('⚠️  错误:'));
          console.log(chalk.gray(this.formatOutput(result.stderr)));
        }

        console.log(chalk.gray(`⏱️  执行时间: ${result.timestamp.toLocaleString()}`));
        console.log(chalk.gray(`🔢 退出码: ${result.exitCode}`));
      });
    }
  }

  private formatOutput(output: string): string {
    // 限制输出长度，避免太长的输出
    const lines = output.split('\n');
    if (lines.length > 10) {
      return lines.slice(0, 10).join('\n') + `\n... (还有${lines.length - 10}行)`;
    }
    return output;
  }

  private async handleTaskError(taskDescription: string, error: Error): Promise<void> {
    try {
      // 这里可以添加错误处理逻辑，比如重试或提供替代方案
      console.log(chalk.yellow('📋 建议检查以下事项:'));
      console.log(chalk.gray('• 检查用户权限是否足够'));
      console.log(chalk.gray('• 确认软件包名称是否正确'));
      console.log(chalk.gray('• 验证网络连接是否正常'));
      console.log(chalk.gray('• 查看系统日志获取更多信息'));

    } catch (analysisError) {
      console.log(chalk.red(`❌ 错误分析失败: ${analysisError}`));
    }
  }

  public async cleanup(): Promise<void> {
    if (this.engine) {
      try {
        await this.engine.cleanup();
      } catch (error) {
        logger.warn(`清理资源时发生错误: ${error}`);
      }
    }
  }
}

// 启动程序
async function main() {
  const cli = new SimpleCLI();

  // 处理程序退出
  process.on('SIGINT', async () => {
    console.log(chalk.yellow('\n\n🛑 收到中断信号，正在清理资源...'));
    await cli.cleanup();
    process.exit(0);
  });

  process.on('SIGTERM', async () => {
    console.log(chalk.yellow('\n\n🛑 收到终止信号，正在清理资源...'));
    await cli.cleanup();
    process.exit(0);
  });

  process.on('uncaughtException', (error) => {
    console.log(chalk.red('\n❌ 未捕获的异常:'), error);
    process.exit(1);
  });

  process.on('unhandledRejection', (reason) => {
    console.log(chalk.red('\n❌ 未处理的Promise拒绝:'), reason);
    process.exit(1);
  });

  await cli.start();
}

main().catch(console.error);